import mistune
from django.views.decorators.csrf import csrf_exempt
from rest_framework.decorators import api_view, renderer_classes
from rest_framework.response import Response
from rest_framework.status import HTTP_200_OK, HTTP_400_BAD_REQUEST

from .models import Blog
from .renderers import UTF8JSONRenderer
from .serializers import BlogSerializers, BlogListSerializers

PAGE_SIZE = 8
headers = {"Access-Control-Allow-Origin": "*"}


@csrf_exempt
@api_view(['GET'])
@renderer_classes([UTF8JSONRenderer])
def blog_list(request):
    if request.method == 'GET':
        blogs = Blog.objects.all().order_by('-pub_date')[:5]
        serializer = BlogListSerializers(blogs, many=True)
        return Response(serializer.data, status=HTTP_200_OK, headers=headers)


@csrf_exempt
@api_view(['GET'])
@renderer_classes([UTF8JSONRenderer])
def blog_detail(request, pk):
    try:
        blog = Blog.objects.get(pk=pk)
        if blog.content != '':
            markdown_html = mistune.Markdown()
            blog.html = markdown_html(blog.content)
    except Blog.DoesNotExist:
        return Response("目标不存在", HTTP_400_BAD_REQUEST, headers=headers)

    if request.method == 'GET':
        serializer = BlogSerializers(blog)
        return Response(serializer.data, status=HTTP_200_OK, headers=headers)
    elif request.method == 'DELETE':
        blog.delete()
        return Response(status=HTTP_200_OK, headers=headers)


@csrf_exempt
@api_view(['GET'])
@renderer_classes([UTF8JSONRenderer])
def blog_pagination(request, page_number, page_size):
    try:
        page_number = int(page_number)
        page_size = int(page_size)
    except TypeError:
        return Response("page_number and page_size must be int", HTTP_400_BAD_REQUEST, headers=headers)

    if page_size == 0:
        page_size = PAGE_SIZE
    start = (page_number - 1) * page_size
    end = start + page_size
    if request.method == 'GET':
        blogs = Blog.objects.all().order_by('-pub_date')[start:end]
        serializer = BlogListSerializers(blogs, many=True)
        return Response(serializer.data, status=HTTP_200_OK, headers=headers)
